package com.winsun.hellozookeeper.server;

import com.winsun.hellozookeeper.util.Constants;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

import java.util.Scanner;

public class ZkServer {
    static ZooKeeper zk;
    static {
        try{
            zk=new ZooKeeper(Constants.ZK_URL,Constants.TIME_OUT,null);
            Stat stat=zk.exists(Constants.ZK_ROOT,false);
            if (stat==null){
                zk.create(Constants.ZK_ROOT,null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    //注册服务
    public static void registerServer(String serverHost){
        try {
            Stat stat=zk.exists(Constants.ZK_ROOT+"/"+serverHost,false);
            if (stat==null){
                zk.create(Constants.ZK_ROOT+"/"+serverHost,null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }
    //移除服务
    public static void removeServer(String serverHost){
        try {
            Stat stat=zk.exists(Constants.ZK_ROOT+"/"+serverHost,false);
            if (stat!=null){
                zk.delete(Constants.ZK_ROOT+"/"+serverHost,-1);//全部
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    //启动服务
    public static void handle(String serverHost){
        new Server(serverHost);
    }

    public static void main(String[] args) {
        registerServer(args[0]);
        handle(args[0]);
        Scanner scanner=new Scanner(System.in);
        String command=scanner.nextLine();
        if ("exit".equals(command)){
            removeServer(args[0]);
            System.exit(0);
        }

    }
}
